package tt.dz.egobus.servicemanager.business.convert;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.connection.Message;
import tt.dz.egobus.servicemanager.bean.RedisTopicMessage;

/**
 * @author Anson
 * @date 17-8-25
 * @name 基于一定业务逻辑的redis的key的转换器
 * @since 1.0.6
 */
public class RedisTopicMessageConverter implements
        Converter<Message, RedisTopicMessage> {

    public static final String SPLIT_KEY = "_";

    @Override
    public RedisTopicMessage convert(Message source) {
        RedisTopicMessage message = new RedisTopicMessage();
        if (source == null) {
            return message;
        }
        String redisOrginalKey = new String(source.getBody());
        if (StringUtils.isAnyEmpty(redisOrginalKey)) {
            return message;
        }
        String[] keys = redisOrginalKey.split(SPLIT_KEY);

        if (keys.length < 4) {
            return message;
        }
        String redisPre=keys[0];
        String eventName=keys[1];
        String businessKey=keys[2];
        long createTime= NumberUtils.toLong(keys[3],System.currentTimeMillis());
        String channel = new String(source.getChannel());
        message.setBusinessKey(businessKey);
        message.setChannel(channel);
        message.setCreateTime(createTime);
        message.setEventName(eventName);
        message.setRedisPre(redisPre);
        return message;
    }


}
